import datetime
import os
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.mongodb import MongoDBJobStore
from apscheduler.triggers.date import DateTrigger
from apscheduler.triggers.interval import IntervalTrigger
from .rpc_spider import RpcSpider
from multiprocessing import Process
from concurrent.futures import ThreadPoolExecutor


scheduler = BackgroundScheduler()
jobstore = MongoDBJobStore(database="RpcScheduler", collection="RpcTask")
scheduler.add_jobstore(jobstore)
scheduler.start()


def pool_task(url=None, task_id=None):
    pool = Process(target=RpcSpider, args=(url, task_id))
    pool.start()
    pool.join()
    return 'success'


def rpc_run(url=None, task_id=None):
    ThreadPoolExecutor(1).submit(pool_task, url, task_id)
    return 'success'


def rpc_stop(pid):
    cmd = 'taskkill /f /t /pid ' + str(pid)
    os.system(cmd)
    return f'stop {pid}'
